# 切分训练集和测试集
import os
import random

trainval_percent = 0.9  # 可自行进行调节 训练验证集占整个数据集的比重
train_percent = 0.9 # 训练集占整个训练验证集的比重
# val_percent = 0.2
xmlfilepath = '../data/Annotations/annotations/xmls'
txtsavepath = '../data/ImageSets/Main'
total_xml = os.listdir(xmlfilepath)

num = len(total_xml) # 总共的数量
print('num:',num)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
# 从列表中截取指定长度
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)

ftrainval = open('../data/ImageSets/Main/trainval.txt', 'w')
ftrain = open('../data/ImageSets/Main/train.txt', 'w')
ftest = open('../data/ImageSets/Main/test.txt', 'w')
fval = open('../data/ImageSets/Main/val.txt','w')

# fval = open('ImageSets/Main/val.txt', 'w')

for i in list:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        ftrainval.write(name)
        if i in train:
            ftrain.write(name)
        else:
            fval.write(name)
    else:
        ftest.write(name)

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()